package com.black.auth.controller;

import com.black.auth.authority.AuthorizationCodeHandler;
import com.black.auth.client.po.OauthClientDetails;
import com.black.auth.client.service.OauthClientDetailsService;
import com.black.auth.util.AesEncryptUtil;
import com.black.common.web.ApiResponse;
import com.black.common.web.ApiResponseBuilder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author linwenfeng
 */
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AuthenticateController {

    private final AuthorizationCodeHandler authorizationCodeHandler;

    private final OauthClientDetailsService oauthClientDetailsService;

    @PostMapping("/oauth/authenticate")
    public ApiResponse<String> authenticate(@RequestBody Map<String, String> parameters) {
        String result;
        try {
            result = authorizationCodeHandler.authenticate(AesEncryptUtil.desEncrypt(parameters.get("username")),
                    AesEncryptUtil.desEncrypt(parameters.get("password")), parameters.get("clientId"));
        } catch (Exception exception) {
            return ApiResponseBuilder.error(exception.getMessage());
        }
        return ApiResponseBuilder.ok(result);
    }

    @GetMapping("/oauth/clientCheck/{clientId}")
    public ApiResponse<OauthClientDetails> getById(@PathVariable("clientId") String clientId) {
        return ApiResponseBuilder.ok(oauthClientDetailsService.findById(clientId));
    }
}
